package com.chuantou.yuba.ui;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.YBApp;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.request.MultiPartRequest;
import com.chuantou.yuba.api.to.CityListTO;
import com.chuantou.yuba.api.to.CityTO;
import com.chuantou.yuba.api.to.UpdateAvatarDataTO;
import com.chuantou.yuba.api.to.UpdateAvatarTO;
import com.chuantou.yuba.api.to.UpdateCoverDataTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.widget.AvatarPickerPopup;
import com.chuantou.yuba.ui.widget.SexPickView;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.DateUtil;
import com.chuantou.yuba.util.ViewHolder;
import com.google.gson.Gson;

/**
 * 注册完善资料界面
 * 
 * @author Administrator
 * 
 */
public class UpdateProfileActivity extends BaseActionBarActivity implements OnClickListener {
	private static final String TAG = UpdateProfileActivity.class.getName();
	private static final int WHAT_REMOVE_ERROR_MSG = 1;
	private ImageView mAddAvatarView;
	private EditText mNicknameView;
	private TextView mBirthdayView;
	private TextView mSexView;
	private TextView mDistrictView;
	private AvatarPickerPopup mPopup;
	private String mAvatarPath;
	private DatePickerDialog mBirthDialog;
	private String mBirthday;
	private AlertDialog mSexDialog;
	private int mSex = -1;
	private List<CityTO> mCities;
	private boolean mIsUpdate = false;
	private TextView mErrorView;
	private CityTO mProvince;
	private CityTO mCity;
	private UserTO mUser;
	private ProgressDialog mDialog = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regist_profile);
		setTitle(R.string.profile);
		setupViews();
		YBApp.get().startLocate(null);
	}

	private void setupViews() {
		mUser = AccountManager.getInstance(getApplicationContext()).getUserTO();
		if (mUser == null) {
			finish();
			return;
		}
		requestCity();
		mAddAvatarView = (ImageView) findViewById(R.id.add_avatar);
		mAddAvatarView.setOnClickListener(this);
		findViewById(R.id.birthday_layout).setOnClickListener(this);
		findViewById(R.id.sex_layout).setOnClickListener(this);
		findViewById(R.id.district_layout).setOnClickListener(this);
		mNicknameView = (EditText) findViewById(R.id.nickname);
		mBirthdayView = (TextView) findViewById(R.id.birthday);
		mSexView = (TextView) findViewById(R.id.sex);
		mDistrictView = (TextView) findViewById(R.id.district);
		mErrorView = (TextView) findViewById(R.id.message);
		setTitleLayoutVisibility(View.GONE);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case WHAT_REMOVE_ERROR_MSG:
				mErrorView.setVisibility(View.GONE);
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add_avatar:
			pickAvatar();
			break;
		case R.id.birthday_layout:
			showBirthDayDialog(v);
			break;
		case R.id.sex_layout:
			showSexDialog(v);
			break;
		case R.id.district_layout:
			showProvinceDialog();
		default:
			break;
		}
	}

	private void showErrorMessage(String msg) {
		mHandler.removeMessages(WHAT_REMOVE_ERROR_MSG);
		mErrorView.setVisibility(View.VISIBLE);
		mErrorView.setText(msg);
		mHandler.sendEmptyMessageDelayed(WHAT_REMOVE_ERROR_MSG, 1500);
	}

	private void requestCity() {
		String url = UriHelper.getCityUrl();
		GsonRequest<CityListTO> request = new GsonRequest<CityListTO>(Method.POST, url, new Listener<CityListTO>() {

			@Override
			public void onResponse(CityListTO response) {
				if (response == null) {
					response = parseLocalCity();
				}
				if (response != null) {
					mCities = response.getCities();
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				CityListTO list = parseLocalCity();
				if (list != null) {
					mCities = list.getCities();
				}
			}
		}, null, CityListTO.class);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	private CityListTO parseLocalCity() {
		try {
			InputStream in = getAssets().open("cities");
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			String str = reader.readLine();
			Gson gson = new Gson();
			return gson.fromJson(str, CityListTO.class);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private void showProvinceDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.choose_district);
		builder.setAdapter(new BaseAdapter() {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					convertView = View.inflate(getApplicationContext(), R.layout.city, null);
				}
				CityTO city = mCities.get(position);
				TextView cityView = ViewHolder.get(convertView, R.id.city);
				cityView.setText(city.getName());
				return convertView;
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public Object getItem(int position) {
				return mCities == null ? null : mCities.get(position);
			}

			@Override
			public int getCount() {
				return mCities == null ? 0 : mCities.size();
			}

		}, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				CityTO cityTO = mCities.get(which);
				showCityDialog(cityTO);
			}
		});
		builder.create().show();
	}

	private void showCityDialog(final CityTO province) {
		final List<CityTO> cities = province.getCities();
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(province.getName());
		builder.setAdapter(new BaseAdapter() {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					convertView = View.inflate(getApplicationContext(), R.layout.city, null);
				}
				CityTO city = cities.get(position);
				TextView cityView = ViewHolder.get(convertView, R.id.city);
				cityView.setText(city.getName());
				return convertView;
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public Object getItem(int position) {
				return cities == null ? null : cities.get(position);
			}

			@Override
			public int getCount() {
				return cities == null ? 0 : cities.size();
			}

		}, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				CityTO cityTO = cities.get(which);
				mProvince = province;
				mCity = cityTO;
				mDistrictView.setText(mCity.getName());
			}
		});
		builder.create().show();
	}

	private void showBirthDayDialog(View view) {
		view.setClickable(false);
		if (mBirthDialog != null && mBirthDialog.isShowing()) {
			return;
		}
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR) - 16;
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		mBirthDialog = new DatePickerDialog(this, mBirthdayChangeListener, year, month, day);
		DatePicker datePicker = mBirthDialog.getDatePicker();
		// 年龄选择16-24岁
		Calendar minCalendar = Calendar.getInstance();
		minCalendar.set(Calendar.YEAR, minCalendar.get(Calendar.YEAR) - 100);
		minCalendar.set(Calendar.MONTH, 0);
		minCalendar.set(Calendar.DAY_OF_MONTH, 0);
		minCalendar.set(Calendar.MINUTE, 0);
		minCalendar.set(Calendar.SECOND, 0);
		minCalendar.set(Calendar.MILLISECOND, 0);
		long minDate = minCalendar.getTimeInMillis();
		datePicker.setMinDate(minDate);
		datePicker.setMaxDate(Calendar.getInstance().getTimeInMillis());
		mBirthDialog.show();
		view.setClickable(true);
	}

	private void showSexDialog(View view) {
		view.setClickable(false);
		if (mSexDialog != null && mSexDialog.isShowing())
			return;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.choose_sex);
		final SexPickView pickView = new SexPickView(getApplicationContext());
		builder.setView(pickView);
		builder.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				int sex = pickView.getSex();
				if (Constants.SEX_FEMALE == sex) {
					mSex = Constants.SEX_FEMALE;
					mSexView.setText(R.string.female);
				} else {
					mSex = Constants.SEX_MALE;
					mSexView.setText(R.string.male);
				}
			}
		});
		mSexDialog = builder.create();
		mSexDialog.show();
		view.setClickable(true);
	}

	private OnDateSetListener mBirthdayChangeListener = new OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.YEAR, year);
			calendar.set(Calendar.MONTH, monthOfYear);
			calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			mBirthday = DateUtil.getDateString(calendar.getTimeInMillis(), DateUtil.PATTERN_YMD);
			mBirthdayView.setText(mBirthday);
		}
	};

	private void pickAvatar() {
		synchronized (TAG) {
			if (mPopup != null && mPopup.isShowing())
				return;
			mPopup = new AvatarPickerPopup(this, true);
			ViewGroup decor = (ViewGroup) getWindow().getDecorView();
			mPopup.showAtLocation(decor, Gravity.BOTTOM, 0, 0);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_done, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_done) {
			update();
		}
		return super.onOptionsItemSelected(item);
	}

	private void update() {
		synchronized (TAG) {
			if (mIsUpdate)
				return;
			String nickname = mNicknameView.getText().toString().trim();
			if (TextUtils.isEmpty(nickname) || nickname.length() < 2) {
				showErrorMessage(getString(R.string.input_nickname_error));
				return;
			}
			if (TextUtils.isEmpty(mBirthday)) {
				showErrorMessage(getString(R.string.input_birthday_error));
				return;
			}
			if (mSex != Constants.SEX_FEMALE && mSex != Constants.SEX_MALE) {
				showErrorMessage(getString(R.string.input_sex_error));
				return;
			}
			if (mProvince == null || mCity == null) {
				showErrorMessage(getString(R.string.input_district_error));
				return;
			}
			mIsUpdate = true;
			showUpdateDialog();
			File avatarFile = null;
			if (!TextUtils.isEmpty(mAvatarPath)) {
				avatarFile = new File(mAvatarPath);
			}
			MultiPartRequest<UpdateAvatarDataTO> request = RequestManager.getUpdateProfileRequest(new Listener<UpdateAvatarDataTO>() {

				@Override
				public void onResponse(UpdateAvatarDataTO response) {
					if (!hasDestroyed()) {
						if (response == null) {
							dismissUpdateDialog();
							showErrorMessage(getString(R.string.server_error));
						} else {
							if (response.isSuccess()) {
								mUser.setAvatar(response.getAvatar());
								mUser.setBirthday(mBirthday);
								mUser.setSex(mSex);
								mUser.setCityId(mCity.getId());
								mUser.setCityName(mCity.getName());
								mUser.setStateId(mProvince.getId());
								mUser.setStateName(mProvince.getName());
								AccountManager.saveUser(getApplicationContext(), mUser);
								Intent intent = new Intent(UpdateProfileActivity.this, MainActivity.class);
								intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
								startActivity(intent);
								sendBroadcast(new Intent(Constants.INTENT_ACITON_LOGIN));
							} else {
								dismissUpdateDialog();
								String msg = response.getMsg();
								msg = TextUtils.isEmpty(msg) ? getString(R.string.regist_error) : msg;
								showErrorMessage(msg);
							}
						}
					}
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					if (!hasDestroyed()) {
						dismissUpdateDialog();
						showErrorMessage(getString(R.string.request_error));
					}
				}
			}, mUser.getUid(), mUser.getToken(), nickname, "", mBirthday, mProvince.getName(), mCity.getName(), 0, "", mSex, avatarFile);
			RequestManager.startUpload(getApplicationContext(), request);
		}
	}

	private void showUpdateDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			return;
		}
		mDialog = new ProgressDialog(this);
		mDialog.setCancelable(false);
		mDialog.setMessage(getString(R.string.submiting));
		mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				mIsUpdate = false;
			}
		});
		mDialog.show();
	}

	private void dismissUpdateDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.dismiss();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		// 根据上面发送过去的请求码来区别
		switch (requestCode) {
		case Constants.REQUEST_CODE_PICK_PHOTO:
		case Constants.REQUEST_CODE_TAKE_PHOTO:
			mAvatarPath = data.getStringExtra("CropperPhotoPath");
			mAddAvatarView.setImageResource(R.drawable.add_avatar);
			mAddAvatarView.setImageURI(Uri.fromFile(new File(mAvatarPath)));
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		YBApp.get().stopLocate(false);
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {

	}
}
